package com.xinghen.rms;

import com.xinghen.core.exception.handler.RmsResponseErrorHandler;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.validation.constraints.NotNull;

/**
 * @author xinghen
 * @ClassName: RmsConfig
 * @Package: com.xinghen.rms
 * @Description config
 * @create 2017-12-08 11:01
 */
@Configuration
@ConfigurationProperties(prefix = "com.xinghen.rms.config")
@Validated
@Data
public class RmsConfig {

    /**
     * rms扫描路径
     */
    @NotNull
    private String rmsPathPatterns;

    /**
     * restTemplate
     *
     * @param requestFactory
     * @return
     */
    @Bean
    @Primary
    @LoadBalanced
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new RmsResponseErrorHandler());
        return restTemplate;
    }

    /**
     * rmsAuthConfigurer
     *
     * @return
     */
    @Bean
    public WebMvcConfigurer rmsAuthConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                String[] rmsPathPatternsArray = rmsPathPatterns.split(",");
                registry.addInterceptor(rmsAuthHandlerInterceptor()).addPathPatterns(rmsPathPatternsArray);
                super.addInterceptors(registry);
            }
        };
    }

    @Bean
    public RmsAuthHandlerInterceptor rmsAuthHandlerInterceptor() {
        return new RmsAuthHandlerInterceptor();
    }

}
